<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

use addons\epay\library\Service as EpayService;
use EasyWeChat\Foundation\Application as WXPAY_APP;
use EasyWeChat\Payment\Order as WXPAY_ORDER;
use addons\third\model\Third;

use app\common\model\Category as CategoryModel;
use app\admin\model\Need;
use app\admin\model\Mission;
use app\admin\model\Data;
use app\admin\model\Tips;
use think\Config;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        // $this->user_id = 1;
    }  

     /**
     * 获取项目类型列表 最多三个级别
     * @ApiReturn ({
        {
  "code": 1,
  "msg": "获取项目类型列表",
  "time": "1595490139",
  "data": [
    {
      "name": "民用建筑",
      "id": 32,
      "child_list": [
        {
          "name": "商业综合体",
          "id": 21,
          "cc_list": [
            {
              "name": "购物中心",
              "id": 22
            }
          ]
        }
      ]
    },
    {
      "name": "其他",
      "id": 33,
      "child_list": []
    }
  ]
}
     })
     */
    public function project_list(){
        $return = [];
        $parent_list = Db::name('category')->where(['type'=>'project','pid'=>0])->field('name,id')->order('weigh desc')->select();
        $return = $parent_list;
        foreach ($parent_list as $key => $value) {
            $return[$key]['child_list'] = Db::name('category')->where(['pid'=>$value['id']])->field('name,id')->order('weigh desc')->select();

            if(!empty($return[$key])){
              foreach ($return[$key]['child_list'] as $k => $v) {
                $cc_list = Db::name('category')->where(['pid'=>$v['id']])->field('name,id')->order('weigh desc')->select();
                if($cc_list)$return[$key]['child_list'][$k]['cc_list'] = $cc_list;
              }
            }
            
        }
        $this->success('获取项目类型列表',$return);
    }

     /**
     * 发布项目需求、需求修改以及需求上下架
     * @ApiSummary  (修改时候再传id过来就好)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/release_need)
     * @ApiParams   (name="id",type=int,required=false,description="项目需求id，上下架的时候传过来")
     * @ApiParams   (name="up_status",type=int,required=false,description="上架时候传1，下架时传-1")
     * @ApiParams   (name="pid",type=int,required=false,description="项目类型id")
     * @ApiParams   (name="title",type=string,required=true,description="标题")
     * @ApiParams   (name="num",type=int,required=false,description="可参与人数")
     * @ApiParams   (name="address",type=string,required=false,description="项目地点")
     * @ApiParams   (name="area",type=int,required=false,description="建筑面积")
     * @ApiParams   (name="detail",type=int,required=false,description="项目需求详情")
     * @ApiParams   (name="phone",type=int,required=false,description="手机号码")
     * @ApiParams   (name="qrcode",type=string,required=false,description="微信二维码")
     * @ApiReturn ({
        
     })
     */
    public function release_need(){
      $params = input();
      $params['user_id'] = $this->user_id;

      if($params['id']){
        $Need = new Need();
        $update = $Need::get($params['id']);

        if($params['up_status']){
          if($params['up_status']=='1'){
            if($update['status']==1)$this->error('当前数据已上架');
            $res =  $update->save(['status'=>1]);
          }else{
            if($update['status']==0)$this->error('当前数据已下架');
            $res =  $update->save(['status'=>0]);
          }
        }else{
          $res = $update->allowField(true)->save($params);
        }
        if($res)$this->success('操作成功');
        $this->error('操作失败');
      }else{
        $Need = new Need($params);
        $res = $Need->allowField(true)->save();
        if($res)$this->success('发布成功');
      }
      
    }

    /**
     * 参与需求
     * @ApiSummary  ()
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/join_need)
     * @ApiParams   (name="need_id",type=int,required=true,description="需求id")
     * @ApiReturn ({
        
     })
     */
    public function join_need(){
      $params = input();
      $Need = new Need();
      $detail = $Need::get($params['need_id']);

      if(empty($detail))$this->error('数据找不到');
      $self_need = Db::name('join_need')->where('user_id',$this->user_id)->column('need_id');
      if($self_need){
        if(in_array($params['need_id'],($self_need)))$this->error('该需求已经参与过了');
      }

      if($detail['remaining']<=0)$this->error('该需求已经达到最大参与人数了');
      if($detail['user_id']==$this->user_id)$this->error('不能参与自己发布的需求');
      
      $now_participants = $detail['participants'].$this->user_id.',';
      $detail->save(['participants'=>$now_participants]);
      $detail->setDec('remaining');

      $join_need = new \app\admin\model\Join_need;
      $join_need->save(['user_id'=>$this->user_id,'need_id'=>$params['need_id']]);
      
      $this->success('参与成功，请等待发布者同意');

    }

    /**
     * 需求列表
     * @ApiSummary  ()
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/index/need_list)
     * @ApiParams   (name="sort_data",type=int,required=false,description="不传就倒叙，传1过来就升序")
     * @ApiReturn ({
        
     })
     */
    public function need_list(){
      input('sort_data')=='1'?$sort_data='asc':$sort_data='desc';
      $need_list = Db::name('need')->where('status',1)->order("updatetime $sort_data")->select();
      $this->success('需求列表',$need_list);
    }



     /**
     * 项目需求详情
     * @ApiSummary  (is_actual_member等于1代表本人已经是合作者了，可以看到微信二维码以及手机号码。is_collect等于1代表已收藏，0就代表未收藏.category_text是分类类型名称)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/need_detail)
     * @ApiParams   (name="id",type=int,required=true,description="项目需求id")
     * @ApiReturn ({
        {
          "code": 1,
          "msg": "项目需求详情",
          "time": "1593575536",
          "data": {
            "id": 2,
            "user_id": 4,
            "address": "广东省佛山市",
            "area": "222",
            "type": "project",
            "pid": "22",
            "detail": "项目需求详情修改后",
            "phone": "18088888888",
            "qrcode": "http://jianzhu.com//uploads/20200630/d7b5f0246c3d0efeb5d20bdb59e0ae40.jpg",
            "participants": null,
            "status": "0",
            "updatetime": 1593575046,
            "weigh": 2,
            "is_collect": 1,
            "status_text": "Status 0",
            "category_text": "民用建筑-商业综合体-购物中心"
          }
        }
     })
     */
    public function need_detail(){
      $need_id = input('id');

      $Need = new Need();
      $detail = $Need::get($need_id);
      if(empty($detail))$this->error('记录没找到');

      if($detail['actual_member']){
        $actual_member = explode(',', rtrim($detail['actual_member'],','));
        if(in_array($this->user_id, $actual_member)){
          $detail['is_actual_member'] = 1;
        }else{
          $detail['is_actual_member'] = 0;
        }
      }else{
          $detail['is_actual_member'] = 0;
      }

       // 是否收藏
      $need_id_json = Db::name('collect')->where('user_id',$this->user_id)->value('need_id');
     
      $need_id_array = json_decode($need_id_json,true);
      if(empty($need_id_array)){
        $detail['is_collect'] = 0;
      }else{
        $key = array_search($detail['id'], $need_id_array);

        if ($key !== false){
          $detail['is_collect'] = 1;
        }else{
          $detail['is_collect'] = 0;
        }
      }
      

      $this->success('项目需求详情',$detail);
    }

     /**
     * 项目需求参与成员列表
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/index/need_member_list)
     * @ApiParams   (name="need_id",type=int,required=true,description="项目需求id")
     * @ApiReturn ({
       
     })
     */
    public function need_member_list(){
      $need_id = input('need_id');

      $Need = new Need();
      $detail = $Need::get($need_id);
      if(empty($detail))$this->error('数据找不到');

      $need_member_list = explode(',', rtrim($detail['participants'],',') );

      $member_list = Db::name('user')->where('id','in',$need_member_list)->field('nickname,avatar,id as user_id')->select();

      $this->success('项目需求参与成员列表',$member_list);
    }

     /**
     * 项目需求选择参与成员作为合作者
     * @ApiSummary  ()
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/index/chose_member)
     * @ApiParams   (name="need_id",type=int,required=true,description="项目需求id")
     * @ApiParams   (name="user_id",type=int,required=true,description="参与者user_id")
     * @ApiReturn ({
       
     })
     */
    public function chose_member(){
      $need_id = input('need_id');
      $user_id = input('user_id');

      $Need = new Need();
      $detail = $Need::get($need_id);
      if(empty($detail))$this->error('数据找不到');

      if($detail['actual_member']){
        $old_actual_member = explode(',', rtrim($detail['actual_member'],',') );
        if(in_array($user_id, $old_actual_member))$this->error('该用户已经是合作者了');
      }

      $need_member_list = explode(',', rtrim($detail['participants'],',') );

      $key = array_keys($need_member_list,$user_id);
      if(empty($key))$this->error('该用户并不是合作候选人');
      if($key){
        $key = $key[0];
      }
      unset($need_member_list[$key]);

      $new_participants = implode(',', $need_member_list);//新的候选人
      $actual_member = $detail['actual_member'].$user_id.',';//入选的新候选人
      $third = Third::where(['user_id' => $user_id, 'platform' => 'wxapp'])->find();
      $send_data['template_id'] = 'r09nlCRmP-bH2Lo-MojbAGsogF8Zgl-_5VmO8MdN6iE';
      $send_data["touser"] = $third['openid'];
      $send_data['data'] = [
        'time3'=>[
          'value' => date('Y年m月d日 H:i:s',time())
        ],
        'thing1' =>[
          'value' => $detail['title']
        ],
        'phrase2' =>[
          'value' => '通过'
        ],
        
      ];
      
      $send_data['page'] = '?need_id='.$need_id;//点击链接跳转的地址

      $res = $this->sendSubMessage($send_data,$this->getAccessToken());
      $res = json_decode($res,true);
      if($res['errmsg']=='ok'){

        $detail->save(['actual_member'=>$actual_member,'participants'=>$new_participants]);
        $this->success('操作成功');
      }else{
        $this->error($res['errmsg']);
      }
    }

    protected function sendSubMessage($params,$token){
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$token;
        $re = $this->curl_url($url,$params);
        return $re;
    }


    protected function curl_url($url, $json)
    { 
        $body = json_encode($json);
        // return $body;
        $headers = array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }

    protected function getAccessToken()
    {
      //当前时间戳
      $now_time = time();

      //失效时间
      $timeout = 7200 ;

      //判断access_token是否过期
      $before_time = $now_time - $timeout;

      //未查找到就为过期
      $access_token = Db::name('access_token')
        ->where('createtime' ,'>',$before_time)
        ->value('access_token');

      if(empty($access_token)){
        $config = get_addon_config('epay');

        $appId= $config['wechat']['miniapp_id'];// 小程序 APPID
        $appSecret = $config['wechat']['app_secret'];//小程序密钥
        $r = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret"); //返回的是字符串，需要用json_decode转换成数组
        $data = json_decode($r,true);
        Db::name('access_token')->insert(['access_token'=>$data['access_token'],'createtime'=>$now_time]);
        return $data['access_token'];
      }
      return $access_token;
      
    }

     /**
     * 发布任务、任务修改以及上下架
     * @ApiSummary  (修改时候再传id过来就好)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/release_mission)
     * @ApiParams   (name="id",type=int,required=false,description="任务id，上下架时候才需要传")
     * @ApiParams   (name="status",type=int,required=false,description="上架时候传1，下架时传 2 ")
     * @ApiParams   (name="title",type=string,required=false,description="任务标题")
     * @ApiParams   (name="due_time",type=string,required=false,description="交付时间")
     * @ApiParams   (name="expiration_date",type=string,required=false,description="有效时间")
     * @ApiParams   (name="expected_price",type=string,required=false,description="预期报酬（元）")
     * @ApiParams   (name="num",type=int,required=false,description="可参与人数")
     * @ApiParams   (name="detail",type=int,required=false,description="任务详情")
     * @ApiParams   (name="phone",type=int,required=false,description="手机号码")
     * @ApiParams   (name="qrcode",type=string,required=false,description="微信二维码")
     * @ApiReturn ({
        
     })
     */
    public function release_mission(){
      $params = input();
      $params['user_id'] = $this->user_id;

      if($params['id']){

        $Mission = new Mission();
        $update = $Mission::get($params['id']);
        
        if($params['status']){
          if($params['status']=='1'){
            if($update['status']==1)$this->error('当前数据已上架');
            $res = $update->save(['status'=>1]);
          }else{
            if($update['status']==0)$this->error('当前数据已下架');
            $res =  $update->save(['status'=>0]);
          }
        }else{
          $res = $update->allowField(true)->save($params);
        }

        if($res)$this->success('操作成功');
        $this->error('操作失败');  

      }else{
        unset($params['status']);
        $Mission = new Mission($params);
        $res = $Mission->allowField(true)->save();
        if($res)$this->success('发布成功');
      }
    }

     /**
     * 任务列表
     * @ApiSummary  ()
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/index/mission_list)
     * @ApiParams   (name="sort_data",type=int,required=false,description="不传就倒叙，传1过来就升序")
     * @ApiReturn ({
        
     })
     */
    public function mission_list(){
      input('sort_data')=='1'?$sort_data='asc':$sort_data='desc';
      $mission_list = Db::name('mission')->where('status',1)->order("updatetime $sort_data")->select();
      $this->success('任务列表',$mission_list);
    }

    /**
     * 参与任务
     * @ApiSummary  (使用优惠券就不用微信支付)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/join_mission)
     * @ApiParams   (name="mission_id",type=int,required=true,description="任务id")
     * @ApiParams   (name="juan_id",type=int,required=false,description="优惠券id")
     * @ApiReturn ({
        
     })
     */
    public function join_mission(){
      $params = input();
      $exist_mission = Db::name('mission')->where('id',$params['mission_id'])->find();
      if(empty($exist_mission))$this->error('数据找不到');

      if($exist_mission['remaining']<=0)$this->error('该任务已经达到最大参与人数了');

      if($exist_mission['user_id']==$this->user_id)$this->error('不能参与自己发布的任务');

      $Order = new \app\common\model\Order;

      $order_detail = $Order->order_add($this->user_id, $params);

      if($order_detail=='2')$this->error('该优惠券已经使用过了');
      if($order_detail=='3')$this->error('该优惠券已经过期');

      if(empty($params['juan_id'])){

        // 发起微信支付
        $this->init_wx_pay_for_wxapp();
     
        $third = Third::where(['user_id' => $this->user_id, 'platform' => 'wxapp'])->find();
    
        $payment = $this->wxapp->payment;
        // halt($payment);
        $attributes = [
            'trade_type'       => 'JSAPI',
            'body'             => Config::get('site.name'),
            'detail'           => Config::get('site.name'),
            'out_trade_no'     => $order_detail['order_no'],
            'openid'           => $third['openid'],
            'total_fee'        => 10000,
            'notify_url'       => Config::get('site.cdnurl').'api/index/callback_for_wxapp',
        ];

        $order_detail = new WXPAY_ORDER($attributes);
      
        $result = $payment->prepare($order_detail);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $config = $payment->configForJSSDKPayment($prepayId); // 返回数组
            return $this->success('订单创建成功,预支付成功',$config);
        }
        return $this->error('微信支付调用失败',$result);
      }

      Db::name('juan')->where('id',$params['juan_id'])->update(['state'=>1]);

      $join_mission = new \app\admin\model\Join_mission;
      $join_mission->save(['user_id'=>$this->user_id,'mission_id'=>$params['mission_id']]);

      $this->success('参与成功');

    }

     /**
     * 任务详情
     * @ApiSummary  (is_collect等于1代表已收藏，0就代表未收藏。if_buy等于1代表已购买，0代表未购买，必须购买了才能查看微信二维码)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/mission_detail)
     * @ApiParams   (name="id",type=int,required=true,description="任务id")
     * @ApiReturn ({
        
     })
     */
    public function mission_detail(){
      $mission_id = input('id');

      $if_buy = Db::name('order')->where('mission_id',$mission_id)->where('pay_status',20)->find();

      $Mission = new Mission();
      $detail = $Mission::get($mission_id);
      if(empty($detail))$this->error('数据找不到');

      $mission_id_json = Db::name('collect')->where('user_id',$this->user_id)->value('mission_id');
      
      $mission_id_array = json_decode($mission_id_json,true);
      if(empty($mission_id_array)){
        $detail['is_collect'] = 0;
      }else{
        $key = array_search($detail['id'], $mission_id_array);
      
        if ($key !== false){
          $detail['is_collect'] = 1;
        }else{
          $detail['is_collect'] = 0;
        }
      }
      
      $if_buy?$detail['if_buy']=1:$detail['if_buy']=0;
      $this->success('任务详情',$detail);
    }

     /**
     * 发布数据、数据修改以及上下架
     * @ApiSummary  (修改时候再传id过来就好,发布后会返回优惠劵)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/release_data)
     * @ApiParams   (name="id",type=int,required=false,description="数据id，上下架时候才需要传")
     * @ApiParams   (name="status",type=int,required=false,description="上架时候传1，下架时传 2 ")
     * @ApiParams   (name="pid",type=int,required=false,description="项目类型id")
     * @ApiParams   (name="title",type=string,required=false,description="数据标题")
     * @ApiParams   (name="design_index",type=int,required=false,description="设计指标:1=土建,2=机电")
     * @ApiParams   (name="detail",type=string,required=false,description="数据详情")
     * @ApiParams   (name="address",type=string,required=false,description="项目地址")
     * @ApiParams   (name="area",type=string,required=false,description="建筑面积(万㎡）")
     * @ApiParams   (name="use_percent",type=string,required=false,description="土建的建筑使用率(单位%)")
     * @ApiParams   (name="metal_percent",type=string,required=false,description="土建的钢筋含量(单位kg)")
     * @ApiParams   (name="metal_str_percent",type=string,required=false,description="土建的钢结构含量(单位kg)")
     * @ApiParams   (name="concrete_percent",type=string,required=false,description="土建的混凝土含量(单位m³）")
     * @ApiParams   (name="park_space",type=string,required=false,description="土建的停车位配建指标(单位个)")
     * @ApiParams   (name="transformer",type=string,required=false,description="机电的变压器装机容量(单位kVA)")
     * @ApiParams   (name="density",type=string,required=false,description="机电的柴发装机密度(单位kW)")
     * @ApiParams   (name="computer_area",type=string,required=false,description="机电的高压配电房、变电所、柴发机房等强电主机房总建筑面(单位㎡)")
     * @ApiParams   (name="ele_room_area",type=string,required=false,description="机电的弱电间、强电间建筑面积(单位㎡)")
     * @ApiParams   (name="engine_room_area",type=string,required=false,description="机电的网络机房、通信机房、消防安防控制室等弱点主机房总建筑面积(单位㎡)")
     * @ApiParams   (name="cold_capacity",type=string,required=false,description="机电的空调冷负荷装机容量(单位kW)")
     * @ApiParams   (name="hot_capacity",type=string,required=false,description="机电的空调热负荷装机容量(单位kW)")
     * @ApiParams   (name="up_cost",type=string,required=false,description="地上建安成本（单位元）")
     * @ApiParams   (name="down_cost",type=string,required=false,description="地下建安成本（单位元）")
     * @ApiParams   (name="outside_decoration",type=string,required=false,description="外装饰工程成本（单位元）")
     * @ApiParams   (name="elevation_decoration",type=string,required=false,description="立面饰面工程成本（单位元）")
     * @ApiParams   (name="company_hardcover_cost",type=string,required=false,description="公司精装成本（单位元）")
     * @ApiParams   (name="up_strong_current",type=string,required=false,description="地上综合成本的强电（单位元）")
     * @ApiParams   (name="up_air_conditioning",type=string,required=false,description="地上综合成本的空调采暖及通风工程（单位元）")
     * @ApiParams   (name="up_fire_engineering",type=string,required=false,description="地上综合成本的消防工程（单位元）")
     * @ApiParams   (name="up_intelligent",type=string,required=false,description="地上综合成本的智能化（单位元）")
     * @ApiParams   (name="up_sum",type=string,required=false,description="地上综合成本的总计（单位元）")
     * @ApiParams   (name="down_strong_current",type=string,required=false,description="地下综合成本的强电（单位元）")
     * @ApiParams   (name="down_air_conditioning",type=string,required=false,description="地下综合成本的空调采暖及通风工程（单位元）")
     * @ApiParams   (name="down_fire_engineering",type=string,required=false,description="地下综合成本的消防工程（单位元）")
     * @ApiParams   (name="down_intelligent",type=string,required=false,description="地下综合成本的智能化（单位元）")
     * @ApiParams   (name="down_sum",type=string,required=false,description="地下综合成本的总计（单位元）")
     * @ApiParams   (name="elevator",type=string,required=false,description="电梯工程（单位元）")
     * @ApiParams   (name="gas",type=string,required=false,description="燃气工程（单位元）")
     * @ApiParams   (name="logistics_decoration",type=string,required=false,description="后期装修（单位元）")
     * @ApiParams   (name="earthwork_foundation",type=string,required=false,description="土方/基础（单位元）")
     * @ApiParams   (name="measures_fee",type=string,required=false,description="措施成本（单位元）")
     * @ApiParams   (name="some_material",type=string,required=false,description="某项材料或者系统名称，数量及总费用(文本框输入）")
     * @ApiReturn ({
        
     })
     */
    public function release_data(){
      $params = input();
      $params['user_id'] = $this->user_id;

      if($params['id']){

        $Data = new Data();
        $update = $Data::get($params['id']);
        
        if($params['status']){
          if($params['status']=='1'){
            if($update['status']==1)$this->error('当前数据已上架');
            $res = $update->save(['status'=>1]);
          }else{
            if($update['status']==0)$this->error('当前数据已下架');
            $res =  $update->save(['status'=>0]);
          }
        }else{
          $res = $update->allowField(true)->save($params);
        }

        if($res)$this->success('操作成功');
        $this->error('操作失败');  

      }else{
        unset($params['status']);
        $Data = new Data($params);
        $res = $Data->allowField(true)->save();

        $juan['user_id'] = $this->user_id;
        $juan['createtime'] = time();
        $juan['updatetime'] = time();

        Db::name('juan')->insert($juan);

        if($res)$this->success('发布成功');
      }
    }

     /**
     * 数据列表
     * @ApiSummary  ()
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/index/data_list)
     * @ApiParams   (name="sort_data",type=int,required=false,description="不传就倒叙，传1过来就升序")
     * @ApiReturn ({
        
     })
     */
    public function data_list(){
      input('sort_data')=='1'?$sort_data='asc':$sort_data='desc';
      $data_list = Db::name('data')->where('status',1)->order("updatetime $sort_data")->select();
      $this->success('数据列表',$data_list);
    }

    /**
     * 数据详情
     * @ApiSummary  (is_collect等于1代表已收藏，0就代表未收藏。)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/data_detail)
     * @ApiParams   (name="id",type=int,required=true,description="数据id")
     * @ApiReturn ({
        
     })
     */
    public function data_detail(){
      $data_id = input('id');

      $Data = new Data();
      $detail = $Data::get($data_id);
      if(empty($detail))$this->error('数据找不到');

      $data_id_json = Db::name('collect')->where('user_id',$this->user_id)->value('data_id');
      
      $data_id_array = json_decode($data_id_json,true);
      if(empty($data_id_array)){
        $detail['is_collect'] = 0;
      }else{
        $key = array_search($detail['id'], $data_id_array);
        if ($key !== false){
          $detail['is_collect'] = 1;
        }else{
          $detail['is_collect'] = 0;
        }
      }
      $this->success('数据详情',$detail);
    }


    /**
     * 提交反馈
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/tips)
     * @ApiParams   (name="type",type=int,required=false,description="问题类型:1=功能异常,2=产品建议,3=其他反馈")
     * @ApiParams   (name="content",type=string,required=false,description="详情")
     */
    public function tips(){
      $params = input();
      $params['user_id'] = $this->user_id;

      $Tips = new Tips($params);
      $res = $Tips->allowField(true)->save();
      if($res)$this->success('提交成功');
    }

    /**
     * 收藏操作 status等于1时候是收藏，0时候是取消收藏。mission_id是任务id。need_id是项目需求id。data_id是数据id
     * @param int $status
     * @param int $mission_id
     * @param int $need_id
     * @param int $data_id
     */
    public function collect(){
      $params = input();

      if($params['mission_id']){

        $pass_data = Db::name('collect')->where('user_id',$this->user_id)->value('mission_id');
        $pass_data_array = json_decode($pass_data,true);

        $data_array = $pass_data_array;

        // 收藏操作
        if($params['status']){

          if($pass_data&&count($pass_data_array)>0){

            $key = array_search($params['mission_id'], $pass_data_array);
            if ($key !== false){
              $this->error('请勿重复操作');
            }else{
              array_unshift($data_array, $params['mission_id']);
            }
          }else{
            $data_array[] = $params['mission_id'];
            
          }

        // 取消收藏
        }else{
          $key = array_search($params['mission_id'], $pass_data_array);
          $data_array = $pass_data_array;
          if ($key !== false){
            unset($data_array[$key]);
          }else{
            $this->error('请勿重复操作');
          }
        }

        $data_json = json_encode($data_array);

        $res = Db::name('collect')->where('user_id',$this->user_id)->update(['mission_id'=>$data_json]); 

      }else if($params['need_id']){
        $pass_data = Db::name('collect')->where('user_id',$this->user_id)->value('need_id');
        $pass_data_array = json_decode($pass_data,true);
        $data_array = $pass_data_array;

        // 收藏操作
        if($params['status']){

          if($pass_data&&count($pass_data_array)>0){
            // halt($params['need_id']);//string类型
            // halt($pass_data_array);
            $key = array_search($params['need_id'], $pass_data_array);
            if ($key !== false){
              $this->error('请勿重复操作');
            }else{
              array_unshift($data_array, $params['need_id']);
            }
          }else{
            $data_array[] = $params['need_id'];
          }

        // 取消收藏
        }else{
          $key = array_search($params['need_id'], $pass_data_array);

          if ($key !== false){
            unset($data_array[$key]);
          }else{
            $this->error('请勿重复操作');
          }
        }
        $data_json = json_encode($data_array);

        $res = Db::name('collect')->where('user_id',$this->user_id)->update(['need_id'=>$data_json]); 

      }else{
        $pass_data = Db::name('collect')->where('user_id',$this->user_id)->value('data_id');
        $pass_data_array = json_decode($pass_data,true);
        $data_array = $pass_data_array;

        // 收藏操作
        if($params['status']){

          if($pass_data&&count($pass_data_array)>0){
            // halt($params['data_id']);//string类型
            // halt($pass_data_array);
            $key = array_search($params['data_id'], $pass_data_array);
            if ($key !== false){
              $this->error('请勿重复操作');
            }else{
              array_unshift($data_array, $params['data_id']);
            }
          }else{
            $data_array[] = $params['data_id'];
          }

        // 取消收藏
        }else{
          $key = array_search($params['data_id'], $pass_data_array);

          if ($key !== false){
            unset($data_array[$key]);
          }else{
            $this->error('请勿重复操作');
          }
        }
        $data_json = json_encode($data_array);

        $res = Db::name('collect')->where('user_id',$this->user_id)->update(['data_id'=>$data_json]); 

      }

      if($res)$this->success('操作成功');
    }


      /**
     * 首页获取数据
     * @ApiSummary  (首页推荐,轮播图)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/index/index)
     * @ApiParams   (name="sort_data",type=int,required=false,description="不传就倒叙，传1过来就升序")
     * @ApiReturn   ({
       
      })
    
     */
    public function index(){
        $banner = Db::name('banner')->order('updatetime desc')->select();

        $need = Db::name('need')->where(['state'=>'1','status'=>'1'])->field("id as need_id,area,num,remaining,title,detail,FROM_UNIXTIME(updatetime,'%Y-%m-%d %H:%i:%s') as updatetime")->order('updatetime desc')->select();

        $mission = Db::name('mission')->where(['state'=>'1','status'=>'1'])->field("id as mission_id,num,remaining,title,detail,FROM_UNIXTIME(updatetime,'%Y-%m-%d %H:%i:%s') as updatetime")->order('updatetime desc')->select();
        $data = Db::name('data')->where(['state'=>'1','status'=>'1'])->field("id as data_id,area,title,detail,FROM_UNIXTIME(updatetime,'%Y-%m-%d %H:%i:%s') as updatetime")->order('updatetime desc')->select();
    
        $return['hot_data'] = array_merge($need,$mission,$data);

        $last_names = array_column($return['hot_data'],'updatetime');
        input('sort_data')=='1'?$sort_data=SORT_ASC:$sort_data=SORT_DESC;
        array_multisort($last_names,$sort_data,$return['hot_data']);

        $return['banner'] = $banner;

        $this->success('首页数据',$return);
    }

    private function init_wx_pay_for_wxapp(){
        $config = get_addon_config('epay');
        $options = [
            'debug'  => false,
            'log' => [
                'level' => 'debug',
                'file'  => LOG_PATH . '/tmp/easywechat.log',
            ],
            'app_id'   => $config['wechat']['miniapp_id'],// 小程序 APPID
            'secret'   => $config['wechat']['app_secret'],//小程序密钥
            'payment' => [
                'merchant_id'        =>  $config['wechat']['mch_id'],//小程序商户号
                'key'                =>  $config['wechat']['key'],//小程序支付密钥
                'notify_url'         =>  \think\Request::instance()->domain().'/api/index/callback_for_wxapp',
            ],

        ];
        $this->wxapp = new WXPAY_APP($options);
    }

     /**
     * 小程序支付回调
     * @ApiSummary  (小程序支付回调)
     * @ApiRoute    (/api/index/callback_for_wxapp)
     */
    protected function callback_for_wxapp(){
        $this->init_wx_pay_for_wxapp();
        $response = $this->wxapp->payment->handleNotify(function($notify, $successful){

            if ($successful) {
                $notify_json = json_encode($notify);
                if ($notify['return_code'] === 'SUCCESS') {
                    if($notify["result_code"] === "SUCCESS"){

                        $order_data = Db::name('order')->where('order_no',$notify->out_trade_no)->find();

                        Db::name('mission')->where('id',$order_data['mission_id'])->setDec('remaining');
                        Db::name('mission')->where('id',$order_data['mission_id'])->setDec('remaining');

                        Db::name('order')->where('order_no',$notify->out_trade_no)->where('pay_status',10)->update([
                            'pay_status' => '20',
                            'pay_time' => time(),
                        ]);

                        $join_mission = new \app\admin\model\join_mission;
                        $join_mission->save(['user_id'=>$order_data['user_id'],'mission_id'=>$order_data['mission_id']]);

                    }
                }
            }

            return true; // 返回处理完成
            
            
        });
        $response->send();
    }

   

    

  

}
